package com.amigo.online.provider.ffmpeg.rocketmq.consumer;

import java.io.*;
import java.nio.file.Files;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.amigo.online.common.core.response.Response;
import com.amigo.online.provider.ffmpeg.entity.UserTbl;
import com.amigo.online.provider.ffmpeg.entity.VideoTbl;
import com.amigo.online.provider.ffmpeg.feignservice.VideoConsumerFeignService;
import com.amigo.online.provider.ffmpeg.util.UploadTempUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import com.amigo.online.provider.ffmpeg.common.ConstantValue;
import com.amigo.online.provider.ffmpeg.feignservice.VideoFeignService;
import com.amigo.online.provider.ffmpeg.rocketmq.PushMessage;
import com.amigo.online.provider.ffmpeg.rocketmq.model.BaseMqSendModel;
import com.amigo.online.provider.ffmpeg.util.FFMpegUtil;
import com.amigo.online.provider.ffmpeg.util.FastDFSClient;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * 视频添加水印消费者
 */
@Component("videoAddWatermarkConsumer")
@Slf4j
public class VideoAddWatermarkConsumer implements PushMessage {

    private static final Logger logger = LoggerFactory.getLogger(VideoAddWatermarkConsumer.class);

    @Autowired
    VideoConsumerFeignService videoConsumerFeignService;

    @Autowired
    FFMpegUtil fFMpegUtil;

    @Autowired
    VideoFeignService videoFeignService;
    @Autowired
    UploadTempUtil uploadTempUtil;
    @Override
    @SuppressWarnings("unchecked")
    public void handleMessage(BaseMqSendModel baseMqSendModel) {
        logger.info("================+ARRIVE-HERE+==================");
        Map<String, Object> map = baseMqSendModel.getSendContentBean(Map.class);
        int width = (int) map.get("width");
        String videoUrl = (String) map.get("video");
        //String videoTitle = (String) map.get("title");
        String videoTitle = videoUrl.substring(16);
        String videoUserAccount = (String) map.get("account");
        Integer userId = (Integer) map.get("userId");
        Integer videoId = (Integer) map.get("id");
        Integer musicId = (Integer) map.get("musicId");
        String waterMarkImg = ConstantValue.LOGO_XXL;
        float logo = (float) width / 180;
        int logo_x = (int) (10 + logo * 2);
        int logo_y = (int) (10 + logo * 2);
        int font_x = (int) (10 + logo * 2);
        int font_y = (int) (10 * logo + 35);
        int fontSize = (int) (8 + logo * 4);
        int scale = (int) (80 + logo * 40);

        StringBuilder videoTempFileBuilder = new StringBuilder(ConstantValue.VIDEO_TMP_PATH).append(videoTitle).append(ConstantValue.MP4);
        List<String> commandList = new LinkedList<>();
        commandList.add(ConstantValue.FFMPEG_PATH);
        commandList.add("-y");
        commandList.add("-i");
        commandList.add(ConstantValue.SERVER_URL + videoUrl);
        commandList.add("-c:v");
        commandList.add("libx264");
        commandList.add("-c:a");
        commandList.add("copy");
        commandList.add("-vf");
        StringBuilder videoCommandBuilder = new StringBuilder(256);
        videoCommandBuilder.append("[in]drawtext=fontfile=").append(ConstantValue.FONT_TYPE).append(":text=\\'ID:")
                .append(videoUserAccount).append("\\':x=").append(font_x).append(":y=").append(font_y)
                .append(":fontsize=").append(fontSize).append(":fontcolor=white")
                //.append(":shadowy=1:shadowcolor=").append(ConstantValue.FONT_COLOR)
                .append("[text];").append("movie=").append(waterMarkImg)
                .append(",scale=").append(scale).append(":-1")//水印图片等比缩放
                .append("[watermark];[text][watermark]overlay=").append(logo_x).append(":").append(logo_y)
                .append("[out]");
        commandList.add(videoCommandBuilder.toString());
        commandList.add(videoTempFileBuilder.toString());
        StringBuilder musicTempFileBuilder = new StringBuilder(100);
        if (musicId == null) {
            musicTempFileBuilder.append(ConstantValue.MUSIC_TMP_PATH).append(videoTitle).append(ConstantValue.MP3);
            commandList.add("-y");
            commandList.add("-f");
            commandList.add("mp3");
            commandList.add("-vn");
            commandList.add(musicTempFileBuilder.toString());
        }
        int duration = fFMpegUtil.dealVideoOperation(commandList);
        logger.info("------------------" + videoId + "-------------------------");
        File videoFile = new File(videoTempFileBuilder.toString());
        if (videoFile.exists()) {
            logger.info("------------------" + videoFile.length() + "时长为:" + duration + "-------------------------");
            MultipartFile mulFile = uploadTempUtil.fileTransformationMultipartFile(videoFile);
            MultipartFile[] m = {mulFile};
            String waterMarkUrl = null;
            //上传加了水印的视频
            try {
                waterMarkUrl = uploadTempUtil.uploadResourceVideo(mulFile);
            } catch (IOException e) {
                log.info("水印视频上传失败",e);
                videoFile.delete();
                return;
            }
            videoFile.delete();
            if (waterMarkUrl != null) {
                logger.info("------------------" + waterMarkUrl + "-------------------------");
//                fFMpegUtil.removeTempFile(videoTempFileBuilder.toString()); //删除,暂时不删
                String musicUrl = "";
                if (musicId == null) {
                    File musicFile = new File(musicTempFileBuilder.toString());
                    //上传音乐文件
                    MultipartFile musicMulFile = uploadTempUtil.fileTransformationMultipartFile(musicFile);
                    try {
                        musicUrl = uploadTempUtil.uploadResourceVideo(musicMulFile);
                    } catch (IOException e) {
                        log.info("水印视频音乐文件上传失败",e);
                        musicFile.delete();
                        return;
                    }
                    musicFile.delete();
                }

                logger.info("---------" + videoId + "---" + waterMarkUrl + "---" + musicUrl + "---" + userId);
                videoFeignService.updateVideoWaterMarkUrlV1(videoId, waterMarkUrl, musicUrl, userId, duration);
            }
        } else {
            logger.error("视频文件异常:" + videoTempFileBuilder.toString());
        }
    }

    /**
     * 给视频加水印
     * @param videoTbl
     * @param userTbl
     */
    public void handleVideo(VideoTbl videoTbl, UserTbl userTbl){
        String waterMarkImg = ConstantValue.LOGO_XXL;
        String videoTitle = videoTbl.getVideo().substring(16);

        float logo = (float) videoTbl.getWidth() / 180;
        int logo_x = (int) (10 + logo * 2);
        int logo_y = (int) (10 + logo * 2);
        int font_x = (int) (10 + logo * 2);
        int font_y = (int) (10 * logo + 35);
        int fontSize = (int) (8 + logo * 4);
        int scale = (int) (80 + logo * 40);
        StringBuilder videoTempFileBuilder = new StringBuilder(ConstantValue.VIDEO_TMP_PATH).append(videoTitle).append(ConstantValue.MP4);
        List<String> commandList = new LinkedList<>();
        commandList.add(ConstantValue.FFMPEG_PATH);
        commandList.add("-y");
        commandList.add("-i");
        commandList.add(ConstantValue.SERVER_URL + videoTbl.getVideo());
        commandList.add("-c:v");
        commandList.add("libx264");
        commandList.add("-c:a");
        commandList.add("copy");
        commandList.add("-vf");
        StringBuilder videoCommandBuilder = new StringBuilder(256);
        videoCommandBuilder.append("[in]drawtext=fontfile=").append(ConstantValue.FONT_TYPE).append(":text=\\'ID:")
                .append(userTbl.getAccount()).append("\\':x=").append(font_x).append(":y=").append(font_y)
                .append(":fontsize=").append(fontSize).append(":fontcolor=white")
                //.append(":shadowy=1:shadowcolor=").append(ConstantValue.FONT_COLOR)
                .append("[text];").append("movie=").append(waterMarkImg)
                .append(",scale=").append(scale).append(":-1")//水印图片等比缩放
                .append("[watermark];[text][watermark]overlay=").append(logo_x).append(":").append(logo_y)
                .append("[out]");
        commandList.add(videoCommandBuilder.toString());
        commandList.add(videoTempFileBuilder.toString());
        StringBuilder musicTempFileBuilder = new StringBuilder(100);
        if (videoTbl.getMusicId() == null) {
            musicTempFileBuilder.append(ConstantValue.MUSIC_TMP_PATH).append(videoTitle).append(ConstantValue.MP3);
            commandList.add("-y");
            commandList.add("-f");
            commandList.add("mp3");
            commandList.add("-vn");
            commandList.add(musicTempFileBuilder.toString());
        }
        int duration = fFMpegUtil.dealVideoOperation(commandList);
        logger.info("------------------" + videoTbl.getId() + "-------------------------");
        File videoFile = new File(videoTempFileBuilder.toString());
        if (videoFile.exists()) {
            logger.info("------------------" + videoFile.length() + "时长为:" + duration + "-------------------------");
            MultipartFile mulFile = uploadTempUtil.fileTransformationMultipartFile(videoFile);
            MultipartFile[] m = {mulFile};
            String waterMarkUrl = null;
            //上传加了水印的视频
            try {
                waterMarkUrl = uploadTempUtil.uploadResourceVideo(mulFile);
            } catch (IOException e) {
                log.info("水印视频上传失败",e);
                videoFile.delete();
                return;
            }
            videoFile.delete();
            if (waterMarkUrl != null) {
                logger.info("------------------" + waterMarkUrl + "-------------------------");
//                fFMpegUtil.removeTempFile(videoTempFileBuilder.toString()); //删除,暂时不删
                String musicUrl = "";
                if (videoTbl.getMusicId() == null) {
                    File musicFile = new File(musicTempFileBuilder.toString());
                    //上传音乐文件
                    MultipartFile musicMulFile = uploadTempUtil.fileTransformationMultipartFile(musicFile);
                    try {
                        musicUrl = uploadTempUtil.uploadResourceVideo(musicMulFile);
                    } catch (IOException e) {
                        log.info("水印视频音乐文件上传失败",e);
                        musicFile.delete();
                        return;
                    }
                    musicFile.delete();
                }

                logger.info("---------" + videoTbl.getId() + "---" + waterMarkUrl + "---" + musicUrl + "---" + userTbl.getId());
                videoFeignService.updateVideoWaterMarkUrlV1(videoTbl.getId(), waterMarkUrl, musicUrl, userTbl.getId(), duration);
            }
        } else {
            logger.error("视频文件异常:" + videoTempFileBuilder.toString());
        }
    }

}
